import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from python_quant.config.sys_config import NotifyMailConfig


class SendMail(object):
    def __init__(self,
                 smtp_receiver,
                 smtp_subject,
                 smtp_body,
                 smtp_file=None):
        """
        to init parameter
        :param smtp_receiver:收件人
        :param smtp_subject:邮件主题
        :param smtp_body:邮件内容
        """
        self.smtp_receiver = smtp_receiver
        self.smtp_subject = smtp_subject
        self.smtp_body = smtp_body
        self.smtp_file = smtp_file

    def mail_content(self):
        """
        to edit mail content
        :return:msg
        """
        if self.smtp_file is not None:
            msg = MIMEMultipart()
            with open(self.smtp_file, 'rb') as fp:
                mail_body = fp.read()
            att = MIMEText(mail_body, "base64", "utf-8")
            att['Conten-Type'] = "application/octet-stream"
            att["Content-Disposition"] = 'attachment; filename="%s"' % self.smtp_file
            msg.attach(att)
            msg.attach(MIMEText(self.smtp_body, "html", "utf-8"))
            msg['from'] = NotifyMailConfig.fromaddr
            msg['to'] = ";".join(self.smtp_receiver)
            msg['subject'] = self.smtp_subject
            return msg
        else:
            msg = MIMEText(self.smtp_body, "html", "utf-8")
            msg['from'] = NotifyMailConfig.fromaddr
            msg['to'] = ";".join(self.smtp_receiver)
            msg['subject'] = self.smtp_subject
            return msg

    def send_mail(self):
        try:
            smtp = smtplib.SMTP()
            smtp.connect(NotifyMailConfig.mailhost[0], NotifyMailConfig.mailhost[1])
            smtp.login(user=NotifyMailConfig.credentials[0], password=NotifyMailConfig.credentials[1])
        except:
            smtp = smtplib.SMTP_SSL(NotifyMailConfig.mailhost[0])
            smtp.connect(NotifyMailConfig.mailhost[0], NotifyMailConfig.mailhost[1])
            smtp.login(user=NotifyMailConfig.credentials[0], password=NotifyMailConfig.credentials[1])
        aaa = self.mail_content()
        try:
            smtp.sendmail(NotifyMailConfig.fromaddr, self.smtp_receiver, aaa.as_string())
            print("发送成功----")
        except Exception as e:
            print("发送失败...", e)
        smtp.quit()
